package com.bifrost.admin.controller;

import com.bifrost.annotation.CurrentAdmin;
import com.bifrost.common.model.ResultModel;
import com.bifrost.entity.OrderItem;
import com.bifrost.entity.User;
import com.bifrost.exception.CancelOrderException;
import com.bifrost.model.order.OrderDetailRO;
import com.bifrost.model.order.OrderDetailVO;
import com.bifrost.model.vo.MerchantStoreVO;
import com.bifrost.model.vo.OrderItemVO;
import com.bifrost.model.vo.OrderVO;
import com.bifrost.model.vo.PageVO;
import com.bifrost.repository.OrderRepository;
import com.bifrost.service.AdminOrderService;
import com.bifrost.service.AdminUserService;
import com.bifrost.service.StoreService;
import com.bifrost.util.DateUtils;
import com.bifrost.util.ExcelReportUtils;
import com.bifrost.util.QueryUtils;
import com.bifrost.util.TransformUtils;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @com.bifrost.admin.controller
 * @wechat-mall
 * @lee Create Class on 2018/4/16
 */
@Api("后台订单相关接口")
@RequestMapping("/admin/order")
@RestController
@Validated
@Slf4j
public class AdminOrderController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdminOrderController.class);

    @Autowired
    AdminOrderService adminOrderService;
    @Autowired
    private AdminUserService userService;
    @Autowired
    OrderRepository orderRepository;
    @Autowired
    StoreService storeService;

    @GetMapping("/page/order")
    @ApiOperation("分页查询订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shippingType", value = "查询条件(配送方式)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "查询条件(品类)", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "orderNumber", value = "查询条件(订单号)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "查询条件(订单状态:CANCELED,PURCHASED)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "merchantStoreIds", value = "查询条件(门店id)", dataType = "数组", paramType = "query"),
            @ApiImplicitParam(name = "skuExternalId", value = "查询条件(商品sap编码)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "productName", value = "查询条件(商品名称)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "查询条件(订单创建时间的左区间)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "查询条件(订单创建时间的右区间)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageCode", value = "当前页(默认为第一页)", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "单页显示条数(默认为10个)", dataType = "int", paramType = "query")
    })
    public ResultModel findByPage(Long categoryId, String shippingType, @CurrentAdmin Long currentUser, String orderNumber, String orderStatus, Long[] merchantStoreIds, String skuExternalId, String productName, String startTime, String endTime, @RequestParam(defaultValue = "1") Integer pageCode, @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            List<Long> merchantStoreIdList = Lists.newArrayList();
            merchantStoreIdList = QueryUtils.getMerchantIds(userService.findById(currentUser), merchantStoreIds);
            PageVO pageVO = adminOrderService.findByPage(categoryId, shippingType, orderNumber, orderStatus, merchantStoreIdList, skuExternalId, productName, startTime, endTime, pageCode, pageSize);
            if (!CollectionUtils.isEmpty(pageVO.getRecordList())) {
                List<OrderItemVO> recordList = pageVO.getRecordList();
                // 按照订单id降序排列
                Collections.sort(recordList, new Comparator<OrderItemVO>() {
                    @Override
                    public int compare(OrderItemVO orderItemVO1, OrderItemVO orderItemVO2) {
                        if (orderItemVO1.getOrderItemId() < orderItemVO2.getOrderItemId()) {
                            return 1;
                        }
                        if (orderItemVO1.getOrderItemId() == orderItemVO2.getOrderItemId()) {
                            return 0;
                        }
                        return -1;
                    }
                });
                return ResultModel.ok().put("customerTagsList", pageVO);
            }
            return ResultModel.error("没有数据");
        } catch (RuntimeException e) {
            log.error(e.getMessage());
            return ResultModel.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return ResultModel.error("出现一些未知错误");
        }
    }


    @GetMapping("/list")
    @ApiOperation("分页查询订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shippingType", value = "查询条件(配送方式)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "查询条件(品类)", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "orderNumber", value = "查询条件(订单号)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "查询条件(订单状态:CANCELED,PURCHASED)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "merchantStoreIds", value = "查询条件(门店id)", dataType = "数组", paramType = "query"),
            @ApiImplicitParam(name = "skuExternalId", value = "查询条件(商品sap编码)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "productName", value = "查询条件(商品名称)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "查询条件(订单创建时间的左区间)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "查询条件(订单创建时间的右区间)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageCode", value = "当前页(默认为第一页)", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "单页显示条数(默认为10个)", dataType = "int", paramType = "query")
    })
    public ResultModel getOrders(Long categoryId, String shippingType, @CurrentAdmin Long currentUser, String orderNumber, String orderStatus, Long[] merchantStoreIds, String skuExternalId, String productName, String startTime, String endTime, String cStartTime, String cEndTime, @RequestParam(defaultValue = "1") Integer pageCode, @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            List<Long> merchantStoreIdList = QueryUtils.getMerchantIds(userService.findById(currentUser), merchantStoreIds);
            PageVO pageVO = adminOrderService.getOrders(cStartTime, cEndTime, categoryId, shippingType, orderNumber, orderStatus, merchantStoreIdList, skuExternalId, productName, startTime, endTime, pageCode, pageSize);
            return CollectionUtils.isNotEmpty(pageVO.getRecordList()) ? ResultModel.ok().put("orders", pageVO) : ResultModel.error("没有数据");
        } catch (RuntimeException e) {
            log.error(e.getMessage());
            return ResultModel.error("没有数据");
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultModel.error("没有数据");
        }
    }

    @ApiOperation("获取订单明细(取货单)")
    @GetMapping("/detail")
    public ResultModel getOrderDetail(@CurrentAdmin Long currentUser, @RequestParam Long orderId){
        User user = userService.findById(currentUser);
        OrderVO orderVO = adminOrderService.getOrderVO(orderId);
        if(null != orderVO){
            orderVO.setOperator(user.getAdminName());
            MerchantStoreVO storeVO = storeService.getMerchantStoreVO(orderVO.getStoreId());
            return ResultModel
                    .ok()
                    .put("date",  DateUtils.format(new Date(),DateUtils.DEFAULT_DATE_FORMAT))
                    .put("order", orderVO)
                    .put("store", storeVO);

        }
        return ResultModel.error("没有数据");
    }

    @ApiOperation("打印退货单")
    @PostMapping("/print")
    public ResultModel printOrderDetail(@CurrentAdmin Long currentUser, @RequestParam Long orderId){
       adminOrderService.updatePrintCount(orderId);
       return ResultModel.ok();
    }

    @ApiOperation("订单明细")
    @PostMapping("/detail/list")
    public ResultModel listDetail(@CurrentAdmin Long userId, @RequestBody OrderDetailRO ro) {
        List<Long> merchantStoreIdList = Lists.newArrayList();
        merchantStoreIdList = QueryUtils.getMerchantIds(userService.findById(userId), ro.getMerchantStoreIds());
        Page<OrderItem> data = adminOrderService.listDetail(ro, merchantStoreIdList);
        if (data != null && data.hasContent()) {
            List<OrderItem> orderItemList = data.getContent();
            if (CollectionUtils.isNotEmpty(orderItemList)) {
                List<OrderDetailVO> orderDetailVOList = new ArrayList<>();
                for (OrderItem orderItem : orderItemList) {
                    OrderDetailVO orderDetailVO = TransformUtils.transformToOrderDetailVO(orderItem);
                    orderDetailVOList.add(orderDetailVO);
                }
                PageVO<OrderDetailVO> pageVO = new PageVO<>
                        (ro.getPageCode(), ro.getPageSize(), (int) data.getTotalElements(), orderDetailVOList);
                return ResultModel.ok().put("pageVO", pageVO);
            }
        }
        return ResultModel.error("没有数据");
    }

    @ApiOperation("订单明细报表")
    @PostMapping("/detail/export")
    public void exportDetail(@CurrentAdmin Long userId, @RequestBody OrderDetailRO ro, HttpServletResponse resp) {
        List<Long> merchantStoreIdList = Lists.newArrayList();
        merchantStoreIdList = QueryUtils.getMerchantIds(userService.findById(userId), ro.getMerchantStoreIds());
        List<OrderItem> orderItemList = adminOrderService.exportDetail(ro, merchantStoreIdList);
        if (CollectionUtils.isNotEmpty(orderItemList)) {
            List<OrderDetailVO> orderDetailVOList = new ArrayList<>();
            int index = 0;
            for (OrderItem orderItem : orderItemList) {
                OrderDetailVO orderDetailVO = TransformUtils.transformToOrderDetailVO(orderItem);
                orderDetailVO.setIndex(++index);
                orderDetailVOList.add(orderDetailVO);
            }
            String title = String.format("订单明细报表");
            ExcelReportUtils.exportExcel(orderDetailVOList, title, "订单明细报表", OrderDetailVO.class, title + ".xls", resp);
        }
    }

    @ApiOperation("取消订单")
    @ApiImplicitParam(paramType = "query", name = "orderId", value = "订单Id", required = true, dataType = "Long")
    @GetMapping("/cancel")
    public ResultModel cancel(@CurrentAdmin Long currentUser, @RequestParam Long orderId) {
        try {
            adminOrderService.cancel(userService.findById(currentUser), orderId);
            return ResultModel.ok("已成功取消订单");
        } catch (CancelOrderException e) {
            LOGGER.error(e.getMessage(), e);
            return ResultModel.error(e.getMessage());
        }
    }

}
